<?php
namespace wechat\models;

use common\components\Pay;
use common\helpers\PayHelper;
use common\helpers\StringHelper;
use common\helpers\UrlHelper;
use common\models\cart\Cart;
use common\models\common\PayLog;
use common\models\order\Order;
use common\models\order\OrderGoods;
use yii\base\Model;
use Yii;
use common\models\member\MemberInfo;
use yii\web\NotFoundHttpException;

/**
 * Class OrderForm
 * @package frontend\models
 */
class OrderForm extends Model
{
    public $store_id;
    public $cart_id;
    public $payment_code;
    public $member_id;
    public $openid;
    public $store_name;
    public $buyer_name;
    public $address_id;

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['payment_code', 'cart_id','member_id','openid','store_id'], 'required'],
            [['member_id','store_id','address_id'],'integer'],
            ['payment_code', 'string', 'max' => 10],
            [['cart_id','openid'],'string'],
            [['buyer_name','store_name'],'string']
        ];
    }

    public function attributeLabels()
    {
        return [
            'payment_code' => '支付方式',
            'cart_id' => '购物清单',
            'member_id' => '用户ID',
            'openid' => 'openid',
            'buyer_name' => '购买人姓名',
            'store_name' => '店铺名称',
            'address_id'=>'地址ID'
        ];
    }

    /**
     * 生成H5订单
     * @return array
     */
    public function addH5(){
        $cart_id = json_decode($this->cart_id,true);
        $cart_list = Cart::find()
            ->where(['in','cart_id',$cart_id])
            ->andWhere(['buyer_id'=>$this->member_id])
            ->with('goods')
            ->asArray()
            ->all();

        if(empty($cart_list))
            return ['status'=>0,'message'=>'商品不能为空','data'=>null];

        $totalFee = 0;// 支付金额单位：分
        $body = [];
        $order_goods = [];
        foreach ($cart_list as $cart){
            $_goods = $cart['goods'];
            $body[] = $cart['goods_name'] . '*' . $cart['goods_num'];
            if($_goods && $_goods['goods_storage'] >= $cart['goods_num']){
                $totalFee += $cart['goods_num'] * $_goods['goods_price'];
                $order_goods[] = [
                    'goods_id' => $_goods['goods_id'],
                    'goods_name' => $_goods['goods_name'],
                    'goods_price' => $_goods['goods_price'],
                    'goods_num' => $cart['goods_num'],
                    'goods_image' => $_goods['goods_image'],
                    'goods_pay_price' => $_goods['goods_price'],
                    'store_id' => $this->store_id,
                    'buyer_id' => $this->member_id,
                    'goods_type' => '1'
                ];
            }else{
                $message = '商品【'.$cart['goods_name'].'】信息有误或库存不足';
                return ['status'=>0,'message'=>$message,'data'=>null];
                break;
            }
        }

        $orderSn = time() . StringHelper::randomNum();// 订单号

        $orderData = [
//            'trade_type' => 'MWEB', // JSAPI，NATIVE，APP,MWEB...
            'body' => implode($body , '，'),
            'detail' => '支付详情',
            'out_trade_no' => PayHelper::getOutTradeNo($totalFee, $orderSn, PayLog::PAY_TYPE_WECHAT), // 支付
            'total_fee' => 1,//$totalFee * 100,
            'notify_url' => 'http://f.huabangkeji.com/notify/wechat.html',//UrlHelper::toFront(['notify/wechat']), // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'openid' => $this->openid, // trade_type=JSAPI，此参数必传，用户在商户appid下的唯一标识，
            // 'auth_code' => 'ojPztwJ5bRWRt_Ipg',  刷卡支付必填
        ];

        // H5支付
        // 原生扫码支付
        $config = Yii::$app->pay->wechat->mweb($orderData);
        $result = $config;
        if ($result['return_code'] != 'FAIL') {
            //生成订单数据
            $model = new Order();
            $model->attributes = [
                'order_sn' => $orderData['out_trade_no'],
                'store_id' => $this->store_id,
                'store_name' => $this->store_name,
                'buyer_id' => $this->member_id,
                'buyer_name' => $this->buyer_name,
                'payment_code' => 'Wechat',
                'goods_amount' => $totalFee,
                'order_amount' => $orderData['total_fee'],
                'order_from'=>2,
                'address_id'=>$this->address_id,
            ];

            $transaction = Yii::$app->db->beginTransaction();
            try {
                if($model->validate() && $model->save()){
                    $order_id = $model->attributes['order_id'];
                    $OrderGoodsModel = new OrderGoods();
                    foreach ($order_goods as $order_goods_item){
                        $order_gooods_model = clone $OrderGoodsModel;
                        $order_goods_item['order_id'] = $order_id;
                        $order_gooods_model->attributes = $order_goods_item;
                        if($order_gooods_model->save()){
                        }else{
                            return ['status'=>0,'message'=>'添加商品事务失败'.json_encode($order_gooods_model->getErrors()),'data'=>null];
                        }
                    }
                    $transaction->commit();
                    return ['status'=>1,'message'=>'','data'=>$config];
                }else{
                    return ['status'=>0,'message'=>json_encode($model->getErrors()),'data'=>null];
                }
            } catch (\Exception $e) {
                $transaction->rollBack();
                return ['status'=>0,'message'=>'添加商品事务失败','data'=>null];
            }
        }else{
            $message = json_encode($result);
            return ['status'=>0,'message'=>$message,'data'=>null];
        }
    }

    /**
     * 生成订单
     * @return array|\yii\db\ActiveRecord[]
     * @throws \yii\base\InvalidConfigException
     */
    public function add()
    {
        $cart_id = json_decode($this->cart_id,true);
        $cart_list = Cart::find()
            ->where(['in','cart_id',$cart_id])
            ->andWhere(['buyer_id'=>$this->member_id])
            ->with('goods')
            ->asArray()
            ->all();

        if(empty($cart_list))
            return ['status'=>0,'message'=>'商品不能为空','data'=>null];

        $totalFee = 0;// 支付金额单位：分
        $body = [];
        $order_goods = [];
        foreach ($cart_list as $cart){
            $_goods = $cart['goods'];
            $body[] = $cart['goods_name'] . '*' . $cart['goods_num'];
            if($_goods && $_goods['goods_storage'] >= $cart['goods_num']){
                $totalFee += $cart['goods_num'] * $_goods['goods_price'];
                $order_goods[] = [
                    'goods_id' => $_goods['goods_id'],
                    'goods_name' => $_goods['goods_name'],
                    'goods_price' => $_goods['goods_price'],
                    'goods_num' => $cart['goods_num'],
                    'goods_image' => $_goods['goods_image'],
                    'goods_pay_price' => $_goods['goods_price'],
                    'store_id' => $this->store_id,
                    'buyer_id' => $this->member_id,
                    'goods_type' => '1'
                ];
            }else{
                $message = '商品【'.$cart['goods_name'].'】信息有误或库存不足';
                return ['status'=>0,'message'=>$message,'data'=>null];
                break;
            }
        }

        $orderSn = time() . StringHelper::randomNum();// 订单号

        $orderData = [
            'trade_type' => 'JSAPI', // JSAPI，NATIVE，APP...
            'body' => implode($body , '，'),
            'detail' => '支付详情',
            'notify_url' => 'http://f.huabangkeji.com/notify/wechat.html',//UrlHelper::toFront(['notify/wechat']), // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'out_trade_no' => PayHelper::getOutTradeNo($totalFee, $orderSn, PayLog::PAY_TYPE_WECHAT), // 支付
            'total_fee' => 1,//$totalFee * 100,
            'openid' => $this->openid, // trade_type=JSAPI，此参数必传，用户在商户appid下的唯一标识，
        ];

        $payment = Yii::$app->wechat->payment;
        $result = $payment->order->unify($orderData);

        if ($result['return_code'] == 'SUCCESS') {
            //生成订单数据
            $model = new Order();
            $model->attributes = [
                'order_sn' => $orderData['out_trade_no'],
                'store_id' => $this->store_id,
                'store_name' => $this->store_name,
                'buyer_id' => $this->member_id,
                'buyer_name' => $this->buyer_name,
                'payment_code' => 'Wechat',
                'goods_amount' => $totalFee,
                'order_amount' => $orderData['total_fee'],
                'order_from'=>2,
                'address_id'=>$this->address_id,
            ];

            $config = $payment->jssdk->sdkConfig($result['prepay_id']);

            $transaction = Yii::$app->db->beginTransaction();
            try {
                if($model->validate() && $model->save()){
                    $order_id = $model->attributes['order_id'];
                    $OrderGoodsModel = new OrderGoods();
                    foreach ($order_goods as $order_goods_item){
                        $order_gooods_model = clone $OrderGoodsModel;
                        $order_goods_item['order_id'] = $order_id;
                        $order_gooods_model->attributes = $order_goods_item;
                        if($order_gooods_model->save()){
                        }else{
                            return ['status'=>0,'message'=>'添加商品事务失败'.json_encode($order_gooods_model->getErrors()),'data'=>null];
                        }
                    }
                    $transaction->commit();
                    return ['status'=>1,'message'=>'','data'=>[
                            'jssdk' => $payment->jssdk,
                            'config' => $config
                        ]
                    ];
                }else{
                    return ['status'=>0,'message'=>json_encode($model->getErrors()),'data'=>null];
                }
            } catch (\Exception $e) {
                $transaction->rollBack();
                return ['status'=>0,'message'=>'添加商品事务失败','data'=>null];
            }
        }else{
            $message = json_encode($result);
            return ['status'=>0,'message'=>$message,'data'=>null];
        }
    }

    /**
     * 注册
     *
     * @return MemberInfo|null
     * @throws \yii\base\Exception
     */
    public function signup()
    {
        $user = new MemberInfo();
        $user->username = $this->username;
        $user->email = $this->email;
        $user->setPassword($this->password);
        $user->generateAuthKey();

        return $user->save() ? $user : null;
    }

}
